package stub

import (
	io "io"
)

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"time"
	"crypto/rand"
	"encoding/hex"
	"strings"
	"net/http"
	"gitee.com/filters/utils/logv"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"sync"
)

const (
	POST    = "POST"
	GET     = "GET"
	DELETE  = "DELETE"
	PUT     = "PUT"
	OPTIONS = "OPTIONS"
	HEAD    = "HEAD"
	PATCH   = "PATCH"
)

// Interceptor 定义拦截器接口
type Interceptor interface {
	Intercept(ctx context.Context, method string, req interface{}) (context.Context, error)
}

// HTTPMethodHandler 定义HTTP方法处理器接口
type HTTPMethodHandler interface {
	HandleGET(w http.ResponseWriter, r *http.Request, path string) error
	HandlePOST(w http.ResponseWriter, r *http.Request, path string) error
	HandleDELETE(w http.ResponseWriter, r *http.Request, path string) error
	HandlePUT(w http.ResponseWriter, r *http.Request, path string) error
}

// DefaultHTTPMethodHandler 默认HTTP方法处理器实现
type DefaultHTTPMethodHandler struct {
	connectHandler http.Handler
}

// HTTPMethodConfig HTTP方法配置
type HTTPMethodConfig struct {
	EnableGET    bool
	EnablePOST   bool
	EnablePUT    bool
	EnableDELETE bool
	EnableCORS   bool
}

// MethodHTTPConfig 定义每个方法支持的HTTP方法
type MethodHTTPConfig struct {
	MethodName     string   // gRPC方法名，如 "Greet", "Hello"
	AllowedMethods []string // 允许的HTTP方法，如 ["GET", "POST", "DELETE"]
}

// NewDefaultHTTPMethodHandler 创建默认HTTP方法处理器
func NewDefaultHTTPMethodHandler(connectHandler http.Handler) *DefaultHTTPMethodHandler {
	return &DefaultHTTPMethodHandler{connectHandler: connectHandler}
}

// DefaultHTTPMethodConfig 默认HTTP方法配置
func DefaultHTTPMethodConfig() *HTTPMethodConfig {
	return &HTTPMethodConfig{
		EnableGET:    true,
		EnablePOST:   true,
		EnablePUT:    true,
		EnableDELETE: true,
		EnableCORS:   true,
	}
}

// GetKeys 获取map的所有key
func GetKeys(m map[string]bool) []string {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	return keys
}

// generateTraceID 生成唯一的trace_id
func generateTraceID() string {
	bytes := make([]byte, 16)
	if _, err := rand.Read(bytes); err != nil {
		// 如果随机数生成失败，使用时间戳作为后备
		return fmt.Sprintf("trace_%d", time.Now().UnixNano())
	}
	return hex.EncodeToString(bytes)
}

// GetTraceIDFromContext 从context中提取trace_id
func GetTraceIDFromContext(ctx context.Context) string {
	// 首先尝试从logv获取
	if traceID := logv.GetTraceID(ctx); traceID != "" {
		return traceID
	}
	// 然后尝试从context value获取
	if tid := ctx.Value("trace_id"); tid != nil {
		if tidStr, ok := tid.(string); ok {
			return tidStr
		}
	}
	// 最后尝试从X-Trace-ID header获取（如果context中有headers）
	if headers := ctx.Value("headers"); headers != nil {
		if headerMap, ok := headers.(map[string][]string); ok {
			if traceHeaders, exists := headerMap["x-trace-id"]; exists && len(traceHeaders) > 0 {
				return traceHeaders[0]
			}
		}
	}
	return ""
}

// HandleGET 处理GET请求
func (h *DefaultHTTPMethodHandler) HandleGET(w http.ResponseWriter, r *http.Request, path string) error {
	// GET请求通常用于查询，可以从URL参数中提取数据
	query := r.URL.Query()

	// 将GET参数转换为JSON格式的POST请求体
	if len(query) > 0 {
		// 创建一个新的POST请求
		newReq := r.Clone(r.Context())
		newReq.Method = "POST"
		newReq.Header.Set("Content-Type", "application/json")

		// 将查询参数转换为JSON
		jsonData := make(map[string]interface{})
		for key, values := range query {
			if len(values) == 1 {
				jsonData[key] = values[0]
			} else {
				jsonData[key] = values
			}
		}

		// 序列化为JSON
		jsonBytes, err := json.Marshal(jsonData)
		if err != nil {
			http.Error(w, "Invalid query parameters", http.StatusBadRequest)
			return err
		}

		// 设置请求体
		newReq.Body = io.NopCloser(bytes.NewReader(jsonBytes))
		newReq.ContentLength = int64(len(jsonBytes))

		// 转发给Connect处理器
		h.connectHandler.ServeHTTP(w, newReq)
		return nil
	}

	// 如果没有查询参数，返回方法信息
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"message":"GET method supported","path":"` + path + `","usage":"Add query parameters for data"}`))
	return nil
}

// HandlePOST 处理POST请求
func (h *DefaultHTTPMethodHandler) HandlePOST(w http.ResponseWriter, r *http.Request, path string) error {
	// POST请求直接转发给Connect处理器
	h.connectHandler.ServeHTTP(w, r)
	return nil
}

// HandleDELETE 处理DELETE请求
func (h *DefaultHTTPMethodHandler) HandleDELETE(w http.ResponseWriter, r *http.Request, path string) error {
	// DELETE请求可以从URL参数或请求体中获取数据
	query := r.URL.Query()

	// 创建一个新的POST请求来处理DELETE逻辑
	newReq := r.Clone(r.Context())
	newReq.Method = POST
	newReq.Header.Set("Content-Type", "application/json")
	newReq.Header.Set("X-HTTP-Method-Override", DELETE)

	// 如果有查询参数，转换为JSON
	if len(query) > 0 {
		jsonData := make(map[string]interface{})
		for key, values := range query {
			if len(values) == 1 {
				jsonData[key] = values[0]
			} else {
				jsonData[key] = values
			}
		}

		jsonBytes, err := json.Marshal(jsonData)
		if err != nil {
			http.Error(w, "Invalid query parameters", http.StatusBadRequest)
			return err
		}

		newReq.Body = io.NopCloser(bytes.NewReader(jsonBytes))
		newReq.ContentLength = int64(len(jsonBytes))
	}

	// 转发给Connect处理器
	h.connectHandler.ServeHTTP(w, newReq)
	return nil
}

// HandlePUT 处理PUT请求
func (h *DefaultHTTPMethodHandler) HandlePUT(w http.ResponseWriter, r *http.Request, path string) error {
	// PUT请求类似POST，但添加方法覆盖头
	newReq := r.Clone(r.Context())
	newReq.Method = POST
	newReq.Header.Set("X-HTTP-Method-Override", PUT)

	// 转发给Connect处理器
	h.connectHandler.ServeHTTP(w, newReq)
	return nil
}

// 全局变量存储当前的 context，用于全局日志钩子
var (
	globalCtx   context.Context
	globalMutex sync.RWMutex
)

// TraceIDHook 是一个 zerolog 钩子，自动为所有日志添加 trace ID
type TraceIDHook struct {
	ctx context.Context
}

// NewTraceIDHook 创建一个新的 TraceID 钩子
func NewTraceIDHook(ctx context.Context) *TraceIDHook {
	return &TraceIDHook{ctx: ctx}
}

// Run 实现 zerolog.Hook 接口
func (h *TraceIDHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
	if h.ctx != nil {
		traceID := GetTraceIDFromContext(h.ctx)
		if traceID != "" {
			e.Str("trace_id", traceID)
		}
	}
}

// LoggerWithTraceID 返回一个带有 trace ID 钩子的日志器
func LoggerWithTraceID(ctx context.Context) *zerolog.Logger {
	hook := NewTraceIDHook(ctx)
	logger := log.Hook(hook)
	return &logger
}

// Info 返回一个自动包含 trace ID 的 Info 级别日志事件
func Info(ctx context.Context) *zerolog.Event {
	logger := LoggerWithTraceID(ctx)
	return logger.Info()
}

// Debug 返回一个自动包含 trace ID 的 Debug 级别日志事件
func Debug(ctx context.Context) *zerolog.Event {
	logger := LoggerWithTraceID(ctx)
	return logger.Debug()
}

// Error 返回一个自动包含 trace ID 的 Error 级别日志事件
func Error(ctx context.Context) *zerolog.Event {
	logger := LoggerWithTraceID(ctx)
	return logger.Error()
}

// Warn 返回一个自动包含 trace ID 的 Warn 级别日志事件
func Warn(ctx context.Context) *zerolog.Event {
	logger := LoggerWithTraceID(ctx)
	return logger.Warn()
}

// Fatal 返回一个自动包含 trace ID 的 Fatal 级别日志事件
func Fatal(ctx context.Context) *zerolog.Event {
	logger := LoggerWithTraceID(ctx)
	return logger.Fatal()
}

// Panic 返回一个自动包含 trace ID 的 Panic 级别日志事件
func Panic(ctx context.Context) *zerolog.Event {
	logger := LoggerWithTraceID(ctx)
	return logger.Panic()
}

// SetGlobalContext 设置全局 context，用于全局日志钩子
func SetGlobalContext(ctx context.Context) {
	globalMutex.Lock()
	defer globalMutex.Unlock()
	globalCtx = ctx
}

// GetGlobalContext 获取全局 context
func GetGlobalContext() context.Context {
	globalMutex.RLock()
	defer globalMutex.RUnlock()
	return globalCtx
}

// GlobalTraceIDHook 全局 trace ID 钩子
type GlobalTraceIDHook struct{}

// Run 实现 zerolog.Hook 接口，从全局 context 中获取 trace_id
func (h *GlobalTraceIDHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
	ctx := GetGlobalContext()
	if ctx != nil {
		traceID := GetTraceIDFromContext(ctx)
		if traceID != "" {
			e.Str("trace_id", traceID)
		}
	}
}

// InitGlobalTraceIDHook 初始化全局 trace ID 钩子
func InitGlobalTraceIDHook() {
	hook := &GlobalTraceIDHook{}
	log.Logger = log.Hook(hook)
}

// MethodInfo 存储方法信息
type MethodInfo struct {
	Name             string
	ProcedurePath    string
	SupportedMethods []string
}

// ServiceInfo 存储服务信息
type ServiceInfo struct {
	ServiceName string
	Methods     []MethodInfo
	BasePath    string
}

// StartupHook 启动钩子函数类型
type StartupHook func() error

type CORSConfig struct {
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	ExposeHeaders    []string
	AllowCredentials bool
	MaxAge           int
}

// CustomRoute 自定义路由结构
type CustomRoute struct {
	Pattern     string
	Handler     http.Handler
	Method      string // 可选，指定HTTP方法
	Description string // 路由描述/注释
}

// ServiceChain 链式服务管理器
type ServiceChain struct {
	mux              *http.ServeMux
	interceptors     []Interceptor
	port             string
	services         []ServiceInfo
	enableRequestLog bool
	printAnnotations bool
	startupHooks     []StartupHook
	corsConfig       *CORSConfig
	enableCORS       bool
	customRoutes     []CustomRoute
	enableTraceLog   bool // 启用trace日志
}

func DefaultCORSConfig() *CORSConfig {
	return &CORSConfig{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH},
		AllowHeaders:     []string{"Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", "x-token"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
		MaxAge:           86400, // 24小时
	}
}

// NewServiceChain 创建新的服务链
func NewServiceChain() *ServiceChain {
	return &ServiceChain{
		mux:              http.NewServeMux(),
		interceptors:     []Interceptor{},
		port:             ":8080",
		services:         []ServiceInfo{},
		enableRequestLog: false,
		printAnnotations: false,
		startupHooks:     []StartupHook{},
		corsConfig:       DefaultCORSConfig(),
		enableCORS:       true, // 默认启用CORS
		customRoutes:     []CustomRoute{},
		enableTraceLog:   false, // 默认关闭trace日志
	}
}

// corsMiddleware CORS中间件
func (sc *ServiceChain) corsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 生成trace_id并添加到请求头和响应头
		traceID := r.Header.Get("X-Trace-ID")
		if traceID == "" {
			traceID = generateTraceID()
		}
		// 将trace_id添加到请求头
		r.Header.Set("X-Trace-ID", traceID)
		// 将trace_id添加到响应头
		w.Header().Set("X-Trace-ID", traceID)
		logv.SetLevel(zerolog.DebugLevel)
		ctx := logv.WithNewTraceID(r.Context())
		r = r.WithContext(ctx)

		// 使用logv记录请求开始
		if sc.enableTraceLog {
			log.Info().Str("trace_id", GetTraceIDFromContext(r.Context())).Str("method", r.Method).Str("path", r.URL.Path).Str("Path", r.URL.Path).Str("remote_addr", r.RemoteAddr).Msg("HTTP请求开始")
		}

		if !sc.enableCORS {
			next.ServeHTTP(w, r)
			return
		}

		config := sc.corsConfig
		origin := r.Header.Get("Origin")

		// 设置允许的源
		if len(config.AllowOrigins) > 0 {
			if config.AllowOrigins[0] == "*" {
				w.Header().Set("Access-Control-Allow-Origin", "*")
			} else {
				for _, allowedOrigin := range config.AllowOrigins {
					if origin == allowedOrigin {
						w.Header().Set("Access-Control-Allow-Origin", origin)
						break
					}
				}
			}
		}

		// 设置允许的方法
		if len(config.AllowMethods) > 0 {
			w.Header().Set("Access-Control-Allow-Methods", strings.Join(config.AllowMethods, ", "))
		}

		// 设置允许的头部
		if len(config.AllowHeaders) > 0 {
			w.Header().Set("Access-Control-Allow-Headers", strings.Join(config.AllowHeaders, ", "))
		}

		// 设置暴露的头部
		if len(config.ExposeHeaders) > 0 {
			w.Header().Set("Access-Control-Expose-Headers", strings.Join(config.ExposeHeaders, ", "))
		}

		// 设置是否允许凭证
		if config.AllowCredentials {
			w.Header().Set("Access-Control-Allow-Credentials", "true")
		}

		// 设置预检请求缓存时间
		if config.MaxAge > 0 {
			w.Header().Set("Access-Control-Max-Age", fmt.Sprintf("%d", config.MaxAge))
		}

		// 处理预检请求
		if r.Method == OPTIONS {
			if sc.enableTraceLog {
				// logv.Info("处理OPTIONS预检请求", "trace_id", traceID)
			}
			w.WriteHeader(http.StatusOK)
			return
		}

		next.ServeHTTP(w, r)
	})
}

// WithCORS 启用/禁用CORS
func (sc *ServiceChain) WithCORS(enable bool) *ServiceChain {
	sc.enableCORS = enable
	return sc
}

// WithCORSConfig 设置自定义CORS配置
func (sc *ServiceChain) WithCORSConfig(config *CORSConfig) *ServiceChain {
	if config != nil {
		sc.corsConfig = config
	}
	return sc
}

// WithCORSOrigins 设置允许的源
func (sc *ServiceChain) WithCORSOrigins(origins ...string) *ServiceChain {
	sc.corsConfig.AllowOrigins = origins
	return sc
}

// WithCORSMethods 设置允许的HTTP方法
func (sc *ServiceChain) WithCORSMethods(methods ...string) *ServiceChain {
	sc.corsConfig.AllowMethods = methods
	return sc
}

// WithCORSHeaders 设置允许的头部
func (sc *ServiceChain) WithCORSHeaders(headers ...string) *ServiceChain {
	sc.corsConfig.AllowHeaders = headers
	return sc
}

// WithInterceptors 添加拦截器
func (sc *ServiceChain) WithInterceptors(interceptors ...Interceptor) *ServiceChain {
	sc.interceptors = append(sc.interceptors, interceptors...)
	return sc
}

// WithPort 设置端口
func (sc *ServiceChain) WithPort(port string) *ServiceChain {
	sc.port = port
	return sc
}

// WithRequestLog 启用/禁用HTTP请求日志
func (sc *ServiceChain) WithRequestLog(enable bool) *ServiceChain {
	sc.enableRequestLog = enable
	return sc
}

// WithFieldAnnotations 启用/禁用字段注解打印
func (sc *ServiceChain) WithFieldAnnotations(enable bool) *ServiceChain {
	sc.printAnnotations = enable
	return sc
}

// WithTraceLog 启用/禁用trace日志
func (sc *ServiceChain) WithTraceLog(enable bool) *ServiceChain {
	sc.enableTraceLog = enable
	return sc
}

// AddStartupHook 添加启动钩子函数
func (sc *ServiceChain) AddStartupHook(hook StartupHook) *ServiceChain {
	sc.startupHooks = append(sc.startupHooks, hook)
	return sc
}

// AddStartupHooks 批量添加启动钩子函数
func (sc *ServiceChain) AddStartupHooks(hooks ...StartupHook) *ServiceChain {
	sc.startupHooks = append(sc.startupHooks, hooks...)
	return sc
}

// AddCustomRoute 添加自定义HTTP路由
func (sc *ServiceChain) AddCustomRoute(pattern string, handler http.Handler) *ServiceChain {
	sc.customRoutes = append(sc.customRoutes, CustomRoute{
		Pattern: pattern,
		Handler: handler,
	})
	return sc
}

// AddCustomRouteWithDescription 添加带注释的自定义HTTP路由
func (sc *ServiceChain) AddCustomRouteWithDescription(pattern string, handler http.Handler, description string) *ServiceChain {
	sc.customRoutes = append(sc.customRoutes, CustomRoute{
		Pattern:     pattern,
		Handler:     handler,
		Description: description,
	})
	return sc
}

// AddCustomRouteWithMethod 添加指定HTTP方法的自定义路由
func (sc *ServiceChain) AddCustomRouteWithMethod(pattern string, method string, handler http.Handler) *ServiceChain {
	sc.customRoutes = append(sc.customRoutes, CustomRoute{
		Pattern: pattern,
		Handler: handler,
		Method:  method,
	})
	return sc
}

// AddCustomRouteWithMethodAndDescription 添加指定HTTP方法和注释的自定义路由
func (sc *ServiceChain) AddCustomRouteWithMethodAndDescription(pattern string, method string, handler http.Handler, description string) *ServiceChain {
	sc.customRoutes = append(sc.customRoutes, CustomRoute{
		Pattern:     pattern,
		Handler:     handler,
		Method:      method,
		Description: description,
	})
	return sc
}

// AddCustomHandlerFunc 添加自定义HandlerFunc路由
func (sc *ServiceChain) AddCustomHandlerFunc(pattern string, handlerFunc http.HandlerFunc) *ServiceChain {
	return sc.AddCustomRoute(pattern, handlerFunc)
}

// AddCustomHandlerFuncWithDescription 添加带注释的自定义HandlerFunc路由
func (sc *ServiceChain) AddCustomHandlerFuncWithDescription(pattern string, handlerFunc http.HandlerFunc, description string) *ServiceChain {
	return sc.AddCustomRouteWithDescription(pattern, handlerFunc, description)
}

// AddRESTEndpoint 添加REST风格的端点
func (sc *ServiceChain) AddRESTEndpoint(basePath string, getHandler, postHandler, putHandler, deleteHandler http.Handler) *ServiceChain {
	if getHandler != nil {
		sc.AddCustomRouteWithMethod(basePath, GET, getHandler)
	}
	if postHandler != nil {
		sc.AddCustomRouteWithMethod(basePath, POST, postHandler)
	}
	if putHandler != nil {
		sc.AddCustomRouteWithMethod(basePath, PUT, putHandler)
	}
	if deleteHandler != nil {
		sc.AddCustomRouteWithMethod(basePath, DELETE, deleteHandler)
	}
	return sc
}

// AddRESTEndpointWithDescription 添加带注释的REST风格端点
func (sc *ServiceChain) AddRESTEndpointWithDescription(basePath string, description string, getHandler, postHandler, putHandler, deleteHandler http.Handler) *ServiceChain {
	if getHandler != nil {
		sc.AddCustomRouteWithMethodAndDescription(basePath, GET, getHandler, description+" - 获取资源")
	}
	if postHandler != nil {
		sc.AddCustomRouteWithMethodAndDescription(basePath, POST, postHandler, description+" - 创建资源")
	}
	if putHandler != nil {
		sc.AddCustomRouteWithMethodAndDescription(basePath, PUT, putHandler, description+" - 更新资源")
	}
	if deleteHandler != nil {
		sc.AddCustomRouteWithMethodAndDescription(basePath, DELETE, deleteHandler, description+" - 删除资源")
	}
	return sc
}

// printAllServices 打印所有注册的服务和方法
func (sc *ServiceChain) printAllServices() {
	fmt.Println("\n📋 已注册的服务和方法:")
	for _, service := range sc.services {
		for _, method := range service.Methods {
			fmt.Printf("         🌐 路径: %s,支持的HTTP方法: %s\n", method.ProcedurePath, strings.Join(method.SupportedMethods, ", "))
		}
	}

	// 显示自定义路由
	if len(sc.customRoutes) > 0 {
		fmt.Println("\n📍 自定义路由:")
		for _, route := range sc.customRoutes {
			methodStr := "ALL"
			if route.Method != "" {
				methodStr = route.Method
			}
			if route.Description != "" {
				fmt.Printf("         🌐 路径: %s,支持的HTTP方法: %s - %s\n", route.Pattern, methodStr, route.Description)
			} else {
				fmt.Printf("         🌐 路径: %s,支持的HTTP方法: %s\n", route.Pattern, methodStr)
			}
		}
	}

	fmt.Printf("\n🚀 服务器启动在: http://localhost%s\n\n", sc.port)
}

// executeStartupHooks 执行所有启动钩子
func (sc *ServiceChain) executeStartupHooks() error {
	fmt.Println("\n🔗 执行启动钩子...")
	for i, hook := range sc.startupHooks {
		fmt.Printf("执行钩子 %d/%d...\n", i+1, len(sc.startupHooks))
		if err := hook(); err != nil {
			fmt.Printf("❌ 钩子 %d 执行失败: %v\n", i+1, err)
			return fmt.Errorf("启动钩子 %d 执行失败: %w", i+1, err)
		}
		fmt.Printf("✅ 钩子 %d 执行成功\n", i+1)
	}
	if len(sc.startupHooks) > 0 {
		fmt.Printf("🎉 所有 %d 个启动钩子执行完成\n", len(sc.startupHooks))
	}
	return nil
}

// registerCustomRoutes 注册自定义路由
func (sc *ServiceChain) registerCustomRoutes() {
	if len(sc.customRoutes) == 0 {
		return
	}

	fmt.Println("\n🔗 注册自定义路由:")
	for _, route := range sc.customRoutes {
		if route.Method != "" {
			// 带HTTP方法限制的路由
			methodHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				if r.Method != route.Method {
					http.Error(w, fmt.Sprintf("Method %s not allowed, expected %s", r.Method, route.Method), http.StatusMethodNotAllowed)
					return
				}
				route.Handler.ServeHTTP(w, r)
			})
			finalHandler := sc.corsMiddleware(methodHandler)
			sc.mux.Handle(route.Pattern, finalHandler)
			if route.Description != "" {
				fmt.Printf("  📍 %s [%s] -> %s\n", route.Pattern, route.Method, route.Description)
			} else {
				fmt.Printf("  📍 %s [%s] -> 自定义处理器\n", route.Pattern, route.Method)
			}
		} else {
			// 不限制HTTP方法的路由
			finalHandler := sc.corsMiddleware(route.Handler)
			sc.mux.Handle(route.Pattern, finalHandler)
			if route.Description != "" {
				fmt.Printf("  📍 %s [ALL] -> %s\n", route.Pattern, route.Description)
			} else {
				fmt.Printf("  📍 %s [ALL] -> 自定义处理器\n", route.Pattern)
			}
		}
	}
}

// Start 启动服务器
func (sc *ServiceChain) Start() error {
	// 执行启动钩子
	if err := sc.executeStartupHooks(); err != nil {
		return err
	}

	// 注册自定义路由
	sc.registerCustomRoutes()

	sc.printAllServices()
	sc.printFieldAnnotations()
	return http.ListenAndServe(sc.port, sc.mux)
}

// printFieldAnnotations 打印所有服务的字段注解
func (sc *ServiceChain) printFieldAnnotations() {
	if !sc.printAnnotations {
		return
	}
	fmt.Println("\n📝 所有服务字段注解信息:")
	fmt.Println(strings.Repeat("=", 60))
	for _, service := range sc.services {
		fmt.Printf("\n🔧 服务: %s\n", service.ServiceName)
		for _, method := range service.Methods {
			fmt.Printf("  📋 方法: %s\n", method.Name)
			fmt.Printf("    🌐 路径: %s\n", method.ProcedurePath)
			fmt.Printf("    📡 HTTP方法: %s\n", strings.Join(method.SupportedMethods, ", "))
		}
	}
	fmt.Println(strings.Repeat("=", 60))
}

// logRequest 记录HTTP请求
func (sc *ServiceChain) logRequest(r *http.Request) {
	if !sc.enableRequestLog {
		return
	}
	fmt.Printf("[%s] 📡 %s %s - %s\n",
		time.Now().Format("2006-01-02 15:04:05"),
		r.Method,
		r.URL.Path,
		r.RemoteAddr)
}

func (sc *ServiceChain) WithHomePage(addr ...string) *ServiceChain {
	defaultAddr := "index.html"
	if len(addr) > 0 && addr[0] != "" {
		defaultAddr = addr[0]
	}
	// 动态生成主页内容
	sc.mux.HandleFunc("/"+defaultAddr, func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		fmt.Fprint(w, `<!DOCTYPE html>
<html>
<head>
<title>文档地址</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.method { margin: 10px 0; padding: 10px; border: 1px solid #ddd; border-radius: 5px; }
.http-methods { color: #666; font-size: 0.9em; }
</style>
</head>
<body>
<h1>🧪 测试链式服务</h1>`)

		// 动态生成服务链接
		for _, service := range sc.services {
			fmt.Fprintf(w, `<h2>🔧 %s</h2>`, service.ServiceName)
			fmt.Fprintf(w, `<p><strong>路径:</strong> %s</p>`, service.BasePath)
			for _, method := range service.Methods {
				fmt.Fprint(w, `<div class="method">`)
				fmt.Fprintf(w, `<h3>%s</h3>`, method.Name)
				fmt.Fprintf(w, `<p><strong>路径:</strong> %s</p>`, method.ProcedurePath)
				fmt.Fprintf(w, `<p class="http-methods"><strong>支持的HTTP方法:</strong> %s</p>`, strings.Join(method.SupportedMethods, ", "))
				// 为每种支持的HTTP方法生成测试链接
				fmt.Fprint(w, `<p><strong>测试链接:</strong> `)
				for i, httpMethod := range method.SupportedMethods {
					if i > 0 {
						fmt.Fprint(w, ` | `)
					}
					if httpMethod == GET {
						fmt.Fprintf(w, `<a href="%s?name=Test" target="_blank">%s</a>`, method.ProcedurePath, httpMethod)
					} else {
						fmt.Fprintf(w, `<span>%s (需要工具测试)</span>`, httpMethod)
					}
				}
				fmt.Fprint(w, `</p>`)
				fmt.Fprint(w, `</div>`)
			}
		}

		fmt.Fprint(w, `</body></html>`)
	})

	return sc
}
